Skip to content

feat(mcp): emerging_signals compares both windows in one Drain tree and reports new variants - #3753

Open
bcanvural wants to merge 4 commits into
ClickHouse:mainfrom
bcanvural:feat/emerging-signals-one-tree
Open

bcanvural wants to merge 4 commits into
ClickHouse:mainfrom
bcanvural:feat/emerging-signals-one-tree

Conversation

@bcanvural

Copy link
Copy Markdown
Contributor

Summary

Refs #3556, #3544 (option 2). Replaces draft #3557, which was stacked on the pre-merge version of #3551; this is the same change on current main.

emerging_signals mines the baseline and current windows in two separate Drain trees and matches their templates as strings. The two trees can generalize the same message differently: a token that is constant in one window stays literal there and becomes <*> in the other, so one unchanged pattern is reported as both "new" and "gone". Date masking (#3551) removed the most common cause; this removes the rest.

This PR:

  • fetches both windows in parallel, then mines them in one TemplateMiner, baseline first, and compares them by cluster id. The order is fixed, so the result doesn't depend on which query finishes first.
  • New variants. One tree can hide a new message that Drain merges into a similar baseline pattern (e.g. user login failed: account locked into user login failed: invalid password). Baseline templates are copied after the baseline is mined. A current row whose cluster came from the baseline but doesn't match that baseline template (token compare, no regex) is reported in emerging with status: "new_variant", baselinePattern, variantShare, and the new line as its sample. Baseline clusters with fewer than 3 sampled rows are skipped.
  • makes the earlier window half-open (dateRangeEndInclusive: false), so a row at the boundary is counted once.

Supporting changes: minePatterns takes an optional miner and returns rowClusterIds (the cluster of each input row); TemplateMiner.tokenize returns the masked tokens Drain compares. mineWindowPatterns is split into fetchWindowSample + mineWindowSample and kept as a wrapper, so event_patterns is unchanged.

Cost: on test data with 100 changed patterns, the variant step takes about 10 ms per 10K rows, and the whole call went from 496 ms to 221 ms (one tree instead of two).

How to reproduce

Starting point: make dev-int.

On main:

  1. Add packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts from this PR.
  2. npx jest src/mcp/__tests__/emergingSignalsOrder.test.ts in packages/api: it fails, because main has no fetchWindowSample / mineWindowSample and reports no new_variant.

On this branch:

  1. emergingSignalsOrder.test.ts passes (17 tests): the login example → new_variant; dated lines on two days → nothing; identical windows → nothing; a token varying only in the current window; same result whichever query finishes first; small baseline clusters skipped; a variant never shows in disappeared.
  2. drain-masking.test.ts (shared miner, rowClusterIds, tokenize) passes; common-utils 3,412, MCP unit 654 and MCP integration (queryTool, emergingSignalsTool, eventPatterns, dashboard) 370 tests pass.

How to test on Vercel preview

N/A — non-UI change.

References

…nd reports new variants

Both windows are mined in one tree, baseline first, and compared by cluster, so
a token that is constant in one window and varies in the other no longer splits
a pattern. New messages that Drain merges into a baseline pattern are found from
Drain's own row assignment with a token compare against the baseline template,
and reported as new_variant. The baseline window excludes its end.
@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c8582fa

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Patch
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Nov 21, 2026

Copy link
Copy Markdown

@bcanvural is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

…-one-tree

# Conflicts:
#	packages/api/src/mcp/tools/query/emergingSignals.ts
#	packages/api/src/mcp/tools/query/runEventPatterns.ts
@bcanvural
bcanvural marked this pull request as ready for review November 24, 2026 09:49
@bcanvural
bcanvural requested a review from a team as a code owner November 24, 2026 09:49
@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

4 finding(s): 🔴 0 P0/P1 · 🟡 2 P2 · 🔵 2 P3

1 posted as inline comment(s) on the changed lines. 1 listed below. 2 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/api/src/mcp/tools/query/emergingSignals.ts:149 — New baselinePattern field is not covered by EMERGING_SIGNALS_REDUCTIONS → pattern is capped at 2000 chars, but baselinePattern is also a full Drain template, which can be very long for stack traces or large bodies when maxBodyChars isn't set. It is never shortened, so trimToolResponse drops whole entries instead. Fix: add { path: 'emerging[].baselinePattern', maxChars: 2000 }.
🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/mcp/tools/query/emergingSignals.ts:378 — Defensive fallbacks for a baseline entry that always exists → variants only gets keys that are in changed, and every key in changed comes from baseline. So baseline.get(key) is never undefined, and b?.tokens ?? [] and b?.sample ?? baselinePattern can never fall back. (Likewise if (cluster) at line 262: the miner's store is unlimited by default.) Fix: store the tokens and sample in changed itself, or assert b is defined, and remove the dead fallbacks.
  • 🔵 P3 packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:161 — The half-open window test only checks the mock's arguments, not the queries → fetchWindowSample is mocked, so the test only proves endExclusive is passed in. It would still pass if fetchWindowSample stopped putting dateRangeEndInclusive: false into the sample or count config (runEventPatterns.ts:228/250). Fix: add a test like the one at searchPartialResults.test.ts:261 that checks the rendered chart configs, or an integration test with a row exactly at the boundary.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

1 similar comment
@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

baseCount: a.baseCount,
sample: b?.sample ?? baselinePattern,
};
if (classifyShift(rest, ratio, newPatternShareFloor) === 'disappeared')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two variant rows hide a surge of the baseline message

Once a cluster has a variant above the floor, rest is only checked for disappeared. If the old message also grows past minShareRatio, that growth is dropped. Only the variant is reported, at its own small share.

Repro, using the helpers in emergingSignalsOrder.test.ts:

it('still reports a baseline message that surged next to a variant', async () => {
  const other = (n: number) =>
    Array.from({ length: n }, (_, i) => `cache warmed in ${i} regions ok`);
  const out = await run(
    [...repeat('payment failed: card declined', 10), ...other(990)],
    [
      ...repeat('payment failed: card declined', 500),
      ...repeat('payment failed: gateway timeout', 2),
      ...other(498),
    ],
  );
  expect(out.emerging).toContainEqual(
    expect.objectContaining({ status: 'shifted', pattern: 'payment failed: card declined' }),
  );
});
  • On this branch: emerging holds only new_variant (payment failed: <*> <*>) at share 0.002. The 0.01 → 0.5 jump of card declined doesn't appear anywhere.
  • Without the 2 gateway timeout rows: the same data reports shifted 0.01 → 0.5.

So 2 rows of a new message can hide a 50x increase in an existing one. That's probably the more important signal of the two.

Two possible fixes:

  1. Classify rest in both directions:
    const restVerdict = classifyShift(rest, ratio, newPatternShareFloor);
    if (restVerdict === 'emerging') emerging.push(rest);
    else if (restVerdict === 'disappeared') disappeared.push(rest);
    This gives a cluster two emerging entries in that case, so "gives one cluster at most one emerging entry" would need to change. I think two entries are correct here, because they are two separate changes.
  2. Keep one entry, but carry the remainder's shift on the variant entry, for example baselineMessageShare: { baseline, current }. Then rank it by the larger of the two swings, so a big surge isn't sorted under a 0.002 variant.

I'd lean toward option 1. The cost is that a cluster can take two emerging slots.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good catch. I went with option 1 in c8582fa. The rest of the cluster is now classified in both directions, so one cluster can have a new_variant entry and a shifted entry. I added your repro as a test (the surge ranks first), and changed the old "at most one emerging entry" test to expect both entries.

I also merged main, since #3742 landed; maxBodyChars now goes through fetchWindowSample.

…-one-tree

# Conflicts:
#	packages/api/src/mcp/tools/query/runEventPatterns.ts
A cluster with a new variant only checked the rest of the cluster for
disappeared, so a surge of the baseline message was dropped: two rows of a
new message could hide a 50x increase of an existing one. Classify the rest
in both directions; a cluster can now take two emerging entries, one per
change.
return;
const v = variants.get(key);
if (v) v.rows++;
else variants.set(key, { rows: 1, sample: raw });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Different new messages in one baseline cluster merge into a single new_variant entry that shows only the first one's sample

variants is keyed by cluster id, and only the first row's body is kept as sample. Take a baseline of GET /api/cart 200 and a current window with 6× GET /api/cart 500 and 6× GET /api/cart 404: you get one entry with pattern GET /api/cart <*> and sample ...500, so the 404s are never shown. This is the same kind of hiding the PR set out to fix. Fix: key variants by cluster plus the masked token sequence (e.g. tokens.join(' ')), or keep several distinct samples per variant.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is intentional: variants are counted per baseline cluster, so one cluster gives at most one new_variant entry. Keying by the masked tokens would give one entry per distinct value of any unmasked token (IDs, hostnames), which can flood emerging. The entry's pattern (GET /api/cart <*>) shows which token varies, the share counts all the new rows, and sample is one example.

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. A full correctness trace confirmed the core algorithm is sound: rowClusterIds[i] aligns 1:1 with sampleRows[i], the variant/rest subtraction never double-counts and stays non-negative, the tokens.length === tmpl.length guard short-circuits before getSeqDistance (so its equal-length throw can't fire), and the half-open boundary de-dups a shared-boundary row exactly once. The prior review's "surge hidden behind a variant" bug is fixed (rest is now classified in both directions) and covered by two tests. Export changes are additive and non-breaking (normalizeTemplate had no remaining callers; minePatterns's new miner/rowClusterIds are optional/additive). The items below are reliability/maintainability hardening and test-coverage recommendations.

🟡 P2 — recommended

  • packages/api/src/mcp/tools/query/emergingSignals.ts:342 — the new one-tree/variant logic calls Drain directly in the handler body (tokenize, getSeqDistance, getCluster().getTemplate()) outside any try/catch, reintroducing the exact "unwrapped Drain throw escapes as an unhandled rejection / 500" failure mode that mineWindowSample's try/catch was added to prevent.
    • Fix: wrap the post-mining block (baseline snapshot through variant detection) in a try/catch that returns mcpServerError(...), matching mineWindowSample's error-union contract.
    • reliability
  • packages/api/src/mcp/tools/query/emergingSignals.ts:342 — the MCP tool reaches through TemplateMiner into miner.drain.* internals (getSeqDistance, the magic === 1 full-similarity value, logTemplateTokens, getCluster) to re-implement match()'s compare, so a future change to Drain's distance semantics would silently diverge here with no compile error.
    • Fix: add a TemplateMiner helper (e.g. fitsTemplate(message, templateTokens)) that owns tokenize + length-check + seq-distance, and call it from the tool.
    • maintainability, correctness
  • packages/api/src/mcp/tools/query/emergingSignals.ts:245 — the error-propagation branches added by the fetch/mine split (if ('error' in curSample/baseSample/baseRes/curRes)) and mineWindowSample's try/catch are never exercised; every test mocks fetchWindowSample to a valid sample.
    • Fix: add a case where the mock resolves to { error: <mcpErrorResult> } (for each window) and assert the tool short-circuits to that error, plus one forcing a Drain throw in mineWindowSample.
    • testing, api-contract, correctness
🔵 P3 nitpicks (9)
  • packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:87 — the mock names its first parameter _teamId, but fetchWindowSample's real first argument is context: McpContext; the misnomer implies a string and would mask a future change to how context is threaded.
    • Fix: rename the mock parameter to _context.
    • testing, maintainability, kieran-typescript
  • packages/api/src/mcp/tools/query/emergingSignals.ts:338 — String(curRes.rowClusterIds.at(i)) coerces a number | undefined to the literal "undefined" key, so any future row/cluster-id desync would silently drop the variant instead of failing loudly.
    • Fix: index with curRes.rowClusterIds[i] (typed number) or assert the two array lengths match.
    • kieran-typescript, correctness
  • packages/api/src/mcp/tools/query/emergingSignals.ts:460 — a new_variant entry's sort key is its own small share (curShare - 0), so with ≥topN larger-swing emerging patterns the detected variant sorts last and is cut by slice(0, topN), dropping the PR's headline signal from the output.
    • Fix: reserve output slots for variant entries or rank them independently of raw share swing.
    • adversarial
  • packages/api/src/mcp/tools/query/emergingSignals.ts:417 — on a new_variant row, pattern is the post-merge generalized template spanning both messages, while the only concrete evidence of the new message is sample; the usage string doesn't tell an agent to read sample/baselinePattern rather than pattern.
    • Fix: note in usage that for new_variant the actionable signal is sample vs baselinePattern.
    • agent-native
  • packages/api/src/mcp/tools/query/emergingSignals.ts:425 — on a new_variant row variantShare always equals currentShare, which usage does not state, risking interpretation as two independent measures.
    • Fix: document that variantShare mirrors currentShare, or drop it as redundant.
    • agent-native
  • packages/api/src/mcp/tools/query/emergingSignals.ts:283 — locals byKey, changed, and rest describe shape rather than intent in an already-dense block.
    • Fix: rename to aggByCluster, generalizedBaselineTemplates, and baselineRemainder.
    • maintainability
  • packages/api/src/mcp/tools/query/runEventPatterns.ts:95 — WindowOptions/WindowSample/MinedWindow are unexported, so ingest's res: typeof curRes leans on control-flow narrowing to name a type it cannot reference directly.
    • Fix: export MinedWindow and annotate ingest(res: MinedWindow, ...).
    • kieran-typescript
  • .changeset/emerging-signals-one-tree.md:6 — the summary uses a bare fix: while sibling MCP changesets scope it (fix(mcp):, feat(mcp):).
    • Fix: change the summary prefix to fix(mcp):.
    • project-standards
  • packages/api/src/mcp/tools/query/emergingSignals.ts:222 — the handler never captures or forwards an abort signal to its two ClickHouse queries, so a client cancellation lets both run to the server-side max_execution_time cap.
    • Fix: thread an abortSignal through fetchOpts if the MCP handler exposes one, as runEventPatterns does.
    • reliability

Reviewers (12): correctness, adversarial, testing, maintainability, project-standards, agent-native, learnings-researcher, performance, kieran-typescript, reliability, api-contract, previous-comments.

Testing gaps:

  • The new_variant happy paths are well covered, but the b.rows >= 3 baseline-skip boundary is only tested at 1 row (not the 2-vs-3 edge), and the "both windows sampled 0 rows" summary.warning branch is unasserted.
  • No unit test pins rowClusterIds index-alignment across two mineWindowSample calls on a shared miner — the exact premise the variant lookup depends on (drain-masking covers only a single call).
  • new_variant firing on routine numeric/literal-token churn (e.g. code 500 → code 404) is intended and tested for field-value cases, but the noise boundary on low-volume/high-cardinality baselines is unpinned; worth a calibration test so the behavior is locked deliberately rather than incidentally. (adversarial, correctness — flagged as a tuning trade-off, not a defect.)
  • Pre-existing (not introduced here): the shifted/gone status values remain undocumented in the tool description/usage, and both tool files already exceed the 300-line guideline.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants